package edu.mama.college.aspect;

import edu.mama.college.model.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
@Slf4j
public class GlobalExceptionAspect {

    @Autowired
    JavaMailSender mailSender;

    @Pointcut("execution(public * edu.mama.college.controller.*.*(..))")
    public void controller() {
    }

//    @AfterThrowing(pointcut = "controller()", throwing = "ex")
//    public void afterThrowing(JoinPoint joinPoint, Exception ex) {
//        //记录异常日志
//        log.error("发生xxxxx异常", ex);
//        //通知开发人员处理
//    }

    @Around("controller()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        try {
            return pjp.proceed();
        } catch (Exception ex) {
            //记录异常日志
            log.error("程序运行抛出异常：", ex);

            //通知开发人员处理
            SimpleMailMessage mail = new SimpleMailMessage();
            mail.setSubject("程序运行抛出异常，请尽快解决");
            mail.setFrom("499218100@qq.com");                            //邮件发送者，这个跟application.yml中设置的要一致
            mail.setTo("499218100@qq.com");                                  //设置邮件接收者，可以有多个接收者，中间用逗号隔开
            mail.setSentDate(new Date());                                   //设置邮件发送日期
            mail.setText(ex.getMessage());                                  //设置邮件的正文
            mailSender.send(mail);                                          //发送邮件

            //返回前端处理失败
            return JsonResult.fail("服务端偶然小恙，请稍后重试");
        }

    }
}
